package top.xwang.firstspringboot.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String fileUpload(String name, MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(name);
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getContentType());

//        String path = request.getServletContext().getRealPath("E:java/upload/");
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);

        saveFile(file, path);
        return "上传成功";
    }

    public void saveFile(MultipartFile file, String path) throws IOException{

        File dir = new File(path);
        System.out.println(dir);
        if (!dir.exists()){
            dir.mkdir();
        }
        File res = new File(path + file.getOriginalFilename());
        file.transferTo(res);
    }
}
